<?php

namespace App\Http\Middleware;

use Closure;

class PermissionMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next, $controller, $action = null)
    {
        if (\Auth::guest()) {
            return redirect('/');
        }

        $permission = $controller;
        if ($action) {
            $permission = $controller . ',' . $action;
        }

        if ($request->user()->can($permission)) {
            return $next($request);
        }

        abort(403);
    }
}
